<?php


namespace app\admin\controller\gou;

use app\common\controller\AdminController;
use EasyAdmin\annotation\ControllerAnnotation;
use EasyAdmin\annotation\NodeAnotation;
use think\App;
use think\facade\Db;

/**
 * @ControllerAnnotation(title="商品出库")
 */
class GoodOutbound extends AdminController
{

    use \app\admin\traits\Curd;
    protected $sort = [
        'id'   => 'desc',
    ];

    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->model = new \app\admin\model\GoodOutbound();
        
    }
    
    /**
     * @NodeAnotation(title="列表")
     */
    public function index()
    {
       if ($this->request->isAjax()) {
            $param = $this->request->param();
        
            list($page, $limit, $where) = $this->buildTableParames();
         
            $where = [];
            if(!empty($param['outbound_no']) && isset($param['outbound_no']))
            {
                $where[] = [
                    ['outbound_no', '=', $param['outbound_no']],
                ];
            }
      
            if(!empty($param['status_time']) && !empty($param['end_time']))
            {
                // $where[] = [
                //     ['good_outbound_time', 'between', [$param['status_time'],$param['end_time']]],
                // ];
               // $where["good_outbound_time"] = ['between', $param["status_time"].','.$param['end_time']];
                $where[] = [
                    ['good_outbound_time','>',$param["status_time"]],
                    ['good_outbound_time','<',$param['end_time']],
                ];
                
            }
            $count = $this->model
                ->where($where)
                ->count();
            $list = $this->model
                ->where($where)
                ->page($page, $limit)
                ->order($this->sort)
                ->select();
                //dump($list->toArray());die;
                foreach ($list as $k => $v){
                    //分类
                    $good_type = Db::name('good_type')->where('id',$v['good_type_id'])->field('title')->find();
                    if(!empty($good_type)){
                        $v['good_type_name'] = $good_type['title'];

                    }else{
                        $v['good_type_name'] ="";
                    }
                    
                    $list[$k] = $v;
                }
            $data = [
                'code'  => 0,
                'msg'   => '',
                'count' => $count,
                'data'  => $list,
            ];
            return json($data);
       }
        $good_type = Db::name("good_type")->order("id desc")->select()->toArray();
        $this->assign("good_type",$good_type);
        return $this->fetch();
    }
    public function array_merge_by_same_key_value($array1,$array2,$key){
        $array = [];
        foreach($array1 as $k1=>$v1){
            foreach($array2 as $k2=>$v2){
                if($v1[$key] == $v2[$key]){
                    $array[$k1]=array_merge($v1,$v2);
                }
            }
        }
        return $array;
    }

    /**
    * @NodeAnotation(title="添加")
    */
    public function add()
    {
        if ($this->request->isAjax()) {
            $session = session("admin");
            $post = $this->request->param();
            if(empty($post['oid'])){
                $this->error('订单不能为空');
            }
         
            if(empty($post['order_no'])){
                $this->error('订单编号不能为空');
            }
            if(empty($post['goodso_item'])){
                $this->error('出库商品不能为空');
            }
            $goodso_item = $post['goodso_item'];

             //判断出库订单详情商品数
             $qworder_item = Db::name("order_item")->where("oid",$post["oid"])->count();
             $cogoodso_item = count($post['goodso_item']);
             if($qworder_item != $cogoodso_item){
                 $this->error('出库数量不正确');
             }
            $order = Db::name("order")->where("id",$post['oid'])->find();
            
            //查询订单商品
           $order_item = Db::name("order_item")->where("oid",$post["oid"])->field("gid,num as nums")->select()->toArray();

           $list = $this->array_merge_by_same_key_value($goodso_item,$order_item,"gid");
           foreach($list as $k=>$v){
                if($v["num"] != $v["nums"] && isset($v["num"]) && isset($v["nums"])){
                    $this->error('出库商品数量不正确');
                }
           }
            $data = [
                'oid'=>$post['oid'],
                'outbound_no'=>$post['outbound_no'],
                'order_no'=>$post['order_no'],
                'outbound_name'=>$post['outbound_name'],
                'outbound_uid'=>$post['outbound_uid'],
                'outbound_username'=>$post['outbound_username'],
                'create_time'=>time(),
                'consignee'=>$post['consignee'],
                'good_outbound_time'=>$post['good_outbound_time'],//remarks
            ];
            try {
                $save = Db::name("good_outbound")->insert($data);
                $goodso_id = Db::name('good_outbound')->getLastInsID();
                Db::name("order")->where("id",$post["oid"])->update(["status"=>6]);
                //添加出库商品信息 
                foreach($goodso_item as $k=>$v){
                    $v["good_outbound_id"] = $goodso_id;
                    unset($v["order_num"]);
                    $goodso_item[$k] = $v;
                }
                Db::name('good_outbound_item')->insertAll($goodso_item); 
                $admin = Db::name("system_admin")->where("id",$session["id"])->find();
                $adminarr = Db::name("system_admin")->where("id",$order["kahuna_id"])->find();
            
                foreach($goodso_item as $k=>$ve){
                    $goods = Db::name("goods")->where("id",$ve["gid"])->find();
                    $good_type = Db::name('good_type')->where('id',$goods['good_type_id'])->field('title')->find();
                     //添加出入库明细
                    $data_crk = [
                        "data_id"=>$goodso_id,//数据id
                        'odd_numbers'=>$post["outbound_no"],//单号
                        "gid"=>$ve["gid"],
                        "good_type_id"=>$goods["good_type_id"],
                        "good_type_name"=>$good_type["title"],
                        "receipt_issue_type"=>3,//1采购入库 2作废入库 3销售出库 4盘赢入库 5盘亏出库
                        "create_time"=>time(),
                        "receipt_issue_num"=>$ve["num"], //出入库数量
                        "tracking_numbercr"=>$order["courier_number"],
                        "discrepancy"=>$admin["employee_name"],//出入库员
                        "order_head"=>$adminarr["employee_name"]//负责人  remarks
                    ];
                    Db::name("receipt_issue_detailed")->insert($data_crk);
                    //修改商品库存
                    Db::name("goods")->where("id",$ve["gid"])->dec("stock",$ve["num"])->update();
                    Db::name("goods")->where("id",$ve["gid"])->inc("sales_volume",$ve["num"])->update();
                }
            } catch (\Exception $e) {
                $this->error('保存失败:' . $e->getMessage());
            }
            $save ? $this->success('保存成功') : $this->error('保存失败');
        }else{
           
            return $this->fetch();
        }
       
    }

    //获取商品出库基础信息
    public function goodout_data(){
        $session = session("admin");
        //出库单号
        $outbound_no = date('Ymd') . substr(implode(null, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8).$session['id'];

        $outbound_time = date("Y-m-d H:i:s",time());

        $outbound_username = $session["username"];//出库人姓名
        $outbound_uid = $session["id"];//出库人id
        
        $res = [
            "outbound_no"=>$outbound_no,
            "outbound_time"=>$outbound_time,
            "outbound_username"=>$outbound_username,
            "outbound_uid"=>$outbound_uid,
        ];
        return json([
            "code"=>1,
            "data"=>$res
        ]);
    }

    //根据发货单条码获取订单，根据商品条码和商品名称获取商品
    public function get_outmgood(){
       // if ($this->request->isAjax()) {
            $param = $this->request->param();
            if(empty($param['type'])){
                $this->error('类型不存在');
            }
           
            $where = [];
            $map = [];
            //type  1订单  2商品
            if($param["type"] == 1){
                if(!empty($param['order_bar_code']))
                {
                    $map = [
                        ['order_no', '=', $param['order_bar_code']],
                    ];
                }
                $order = Db::name("order")->where($map)->find();
                if(empty($order)){
                    $this->error('订单不存在');
                }
                $ore_gfag = Db::name("good_outbound")->where("oid",$order['id'])->find();
                if(!empty($ore_gfag)){
                    $this->error('订单已出库');
                }
                $order_item = Db::name("order_item")->where("oid",$order["id"])->select()->toArray();

                //查询录入商品
                $good_outbound_view = Db::name("good_outbound_view")->where("oid",$order["id"])->select()->toArray();

                //判断订单商品是否已录入
                if(empty($good_outbound_view)){
                    foreach ($order_item as $k => $v){
                        $good = Db::name("goods")->where("id",$v["gid"])->find();
                        $data_o = [
                            "oid"=>$order["id"],
                            "gid"=>$good["id"],
                            "good_name"=>$good["title"],
                            "order_num"=>$v["num"],
                        ];
                        Db::name("good_outbound_view")->insert($data_o);
                    }
                } 
                // //未出库数量
                // $w_Outbound_num = Db::name("order_item")->where("oid",$order["id"])->where("is_outbound",1)->count();

                // //已出库数量
                // $y_Outbound_num = Db::name("order_item")->where("oid",$order["id"])->where("is_outbound",2)->count();
                
                //已录入商品
                $good_outbound_view = Db::name("good_outbound_view")->where("oid",$order["id"])->field("gid,good_name,stock,num,order_num")->select()->toArray();
                // foreach ($good_outbound_view as $k => $v){
                //     $good = Db::name("goods")->where("id",$v["gid"])->find();
                //     //分类
                //     $good_type = Db::name('good_type')->where('id',$good['good_type_id'])->field('title')->find();
                //     $v['good_type_name'] = $good_type['title'];
                //     $v['good_type_id'] = $good['good_type_id'];
                //     $good_outbound_view[$k] = $v;
                // }
    
                //$order["order_item"] = $order_item;
                // $order["w_Outbound_num"] = $w_Outbound_num;
                // $order["y_Outbound_num"] = $y_Outbound_num;
                $order["good_outbound_view"] = $good_outbound_view;
                $this->success('订单获取成功',$order);
            }elseif($param["type"] == 2){
                // if(!empty($param['keyword']))
                // {
                //     $where[] = [
                //         ['bar_code', '=', $param['bar_code']],
                //         ['good_name', '=', $param['good_name']]
                //     ];
                // }
                if(empty($param['oid'])){
                    $this->error('订单id不存在');
                }
                $goods = $this->getFuzzySearchResult($param['keyword']);
                
                if(empty($goods)){
                    $this->error('商品不存在');
                }
                $order_item = Db::name("order_item")->where("oid",$param["oid"])->where("gid",$goods["id"])->find();
                if(empty($order_item)){
                    $this->error('此商品不在订单中');
                }

                $flag = Db::name("good_outbound_view")->where("oid",$param["oid"])->where("gid",$goods["id"])->find();
                if(empty($flag)){
                    $this->error('商品未录入');
                    // $data_t = [
                    //     "oid"=>$param["oid"],
                    //     "good_name"=>$goods["title"],
                    //     "gid"=>$goods["id"],
                    //     "stock"=>$goods["stock"],
                    //     "num"=>1,
                    // ];
                    // Db::name("good_outbound_view")->insert($data_t);
                }else{
                    $asf = Db::name("good_outbound_view")->where("oid",$param["oid"])->where("gid",$goods["id"])->find();
                    if($asf["num"] == $asf["order_num"]){
                        $this->error('数量已超出');
                    }
                    Db::name("good_outbound_view")->where("oid",$param["oid"])->where("gid",$goods["id"])->inc("num",1)->update();
                }

                //修改订单详情出库状态
                Db::name("order_item")->where("oid",$param["oid"])->where("gid",$goods["id"])->update(["is_outbound"=>2]);

                // //更新未出库数量
                // $w_Outbound_num = Db::name("order_item")->where("oid",$param["oid"])->where("is_outbound",1)->count();

                // //更新已出库数量
                // $y_Outbound_num = Db::name("order_item")->where("oid",$param["oid"])->where("is_outbound",2)->count();

                $good_outbound_view = Db::name("good_outbound_view")->where("oid",$param["oid"])->field("gid,good_name,stock,num,order_num")->select()->toArray();

              
                
                $res_good = [
                    // "w_Outbound_num"=>$w_Outbound_num,
                    // "y_Outbound_num"=>$y_Outbound_num,
                    "good_outbound_view"=>$good_outbound_view,
                ];
                
                $this->success('商品获取成功',$res_good);
            }else{
                $this->error('类型不存在');
            }
            
           
      //  }
    }

    public function getFuzzySearchResult($keyword){

        $result = Db::name("goods")->where("status",0)
                        ->where('bar_code', 'like', '%'.$keyword.'%')  //在bar_code字段中进行模糊查询
                        ->whereOr('title', 'like', '%'.$keyword.'%')  //在title字段中进行模糊查询
                        ->field("id,title,stock")
                        ->find();
        return $result;
    
    }

    //更改出库商品数量
    public function ga_goodnum(){
        if ($this->request->isAjax()) {
            $post = $this->request->param();
            if(empty($post['oid'])){
                $this->error('订单id不能为空');
            }
            if(empty($post['gid'])){
                $this->error('商品id不能为空');
            }
            if(empty($post['num'])){
                $this->error('数量不能为空');
            }
           
            Db::name("good_outbound_view")->where("oid",$post["oid"])->where("gid",$post["gid"])->update(["num"=>$post["num"]]);
            
            $good_outbound_view = Db::name("good_outbound_view")->where("oid",$post["oid"])->field("gid,good_name,stock,num")->select()->toArray();
           
            $this->success('操作成功',$good_outbound_view);
        }
    }
 
    //出库商品删除
    public function outbound_gooddel(){
        if ($this->request->isAjax()) {
            $post = $this->request->param();
            if(empty($post['oid'])){
                $this->error('订单id不能为空');
            }
            if(empty($post['gid'])){
                $this->error('商品id不能为空');
            }
            Db::name("order_item")->where("oid",$post["oid"])->where("gid",$post["gid"])->update(["is_outbound"=>1]);

            Db::name("good_outbound_view")->where("oid",$post["oid"])->where("gid",$post["gid"])->delete();

            //最新未出库数量
            $w_Outbound_num = Db::name("order_item")->where("oid",$post["oid"])->where("is_outbound",1)->count();

            //最新已出库数量
            $y_Outbound_num = Db::name("order_item")->where("oid",$post["oid"])->where("is_outbound",2)->count();

            $good_outbound_view = Db::name("good_outbound_view")->where("oid",$post["oid"])->field("gid,good_name,stock,num")->select()->toArray();
            $res = [
                "w_Outbound_num"=>$w_Outbound_num,
                "y_Outbound_num"=>$y_Outbound_num,
                "good_outbound_view"=>$good_outbound_view,
            ];
            $this->success('操作成功',$res) ;
        }
    }

    //编辑备注
    public function edit_outboundremark(){
        if ($this->request->isAjax()) {
            $post = $this->request->param();
            if(empty($post['remarks'])){
                $this->error('参数不能为空');
            }
            Db::name("good_outbound")->where("id",$post["id"])->update(["remarks"=>$post["remarks"]]);
            $this->success('编辑成功') ;
        }else{
            return $this->fetch();
        }
    }

    //出库单详情
    public function goodo_detail(){
        $param = $this->request->param();
        $row = Db::name("good_outbound")->where("id",$param["id"])->find();
 
        $good_outbound_item = Db::name("good_outbound_item")->where("good_outbound_id",$param["id"])->select()->toArray();
 
        $row["good_outbound_item"] = $good_outbound_item;
        return json([
            "code"=>1,
            "data"=>$row
        ]);
    }


       
    
 
} 